﻿using egg;
using Egg;
using Microsoft.EntityFrameworkCore;
using ModularCenter.Dto;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ModularCenter
{
    public partial class FrmParent : Form
    {
        private int childFormNumber = 0;
        private readonly string _folder;
        private readonly FrmProject _frmProject;
        private readonly FrmConsole _frmConsole;
        private readonly FrmConsoleOutput _frmConsoleOutput;

        /// <summary>
        /// 设置信息
        /// </summary>
        public Setting Setting { get; private set; }

        /// <summary>
        /// 模拟控制台
        /// </summary>
        public FrmConsoleOutput Console => _frmConsoleOutput;

        /// <summary>
        /// 工作目录
        /// </summary>
        public string WorkFolder { get { return _folder; } }

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="content"></param>
        /// <param name="wait"></param>
        private void SetStatus(string content, int wait = 0)
        {
            this.toolStripStatusLabel.Text = content;
            Application.DoEvents();
            if (wait > 0) Thread.Sleep(wait);
        }

        public FrmParent(string? folder = null)
        {
            if (folder.IsEmpty())
            {
                _folder = egg.Assembly.WorkingDirectory;
            }
            else
            {
                _folder = folder ?? "";
            }
            InitializeComponent();
            // 初始化模拟控制台
            _frmConsole = new FrmConsole(_folder);
            _frmConsole.MdiParent = this;
            _frmConsoleOutput = new FrmConsoleOutput(_frmConsole);
            Coder.ModuleMaker.Output = _frmConsoleOutput;
            // 初始化项目窗口
            _frmProject = new FrmProject();
            _frmProject.MdiParent = this;
            _frmProject.ControlBox = false;
            _frmProject.Text = "项目资源";
            _frmProject.Size = new Size(400, 500);
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            Form childForm = new Form();
            childForm.MdiParent = this;
            childForm.Text = "窗口 " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //openFileDialog.Filter = "Modular Center Config文件(*.mcc)|*.mcc";
            //if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    string FileName = openFileDialog.FileName;
            //}
            using (FolderBrowserDialog f = new FolderBrowserDialog())
            {
                f.SelectedPath = _folder;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    this.Setting.ProjectPath = f.SelectedPath;
                    this.Setting.ProjectName = System.IO.Path.GetFileName(f.SelectedPath);
                    this.SaveConfig();
                    _frmProject.Reload();
                }
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Modular Center Config文件(*.mcc)|*.mcc";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void FrmParent_Load(object sender, EventArgs e)
        {
            this.Text = $"{egg.Assembly.Name} Ver:{egg.Assembly.Version} - [{_folder}]";
            this.LoadConfig();
            // 隐藏菜单
            this.windowsMenu.Visible = false;
            this.editMenu.Visible = false;
            // 显示项目资源窗口
            _frmProject.Reload();
            _frmProject.Show();
            // Debug.WriteLine($"this.DisplayRectangle.Width: {this.DisplayRectangle.Width}");
            _frmConsole.Show();
            _frmConsole.Location = new Point(this.DisplayRectangle.Width - _frmConsole.Width - 30, this.DisplayRectangle.Height - _frmConsole.Height - 100);
        }

        private void SaveConfig()
        {
            string cfgPath = _folder + ".modular";
            this.Setting.SaveToFile(egg.IO.GetClosedPath(cfgPath) + "setting.json");
        }

        private void LoadConfig()
        {
            string cfgPath = _folder + ".modular";
            //string dbPath = $"{egg.IO.GetClosedPath(cfgPath)}data.db";
            //string connStr = $"Data Source={dbPath};";
            // 创建目录
            if (!egg.IO.CheckFolderExists(cfgPath))
            {
                // 创建目录
                egg.IO.CreateFolder(cfgPath);
                // 兼容Windows隐藏
                File.SetAttributes(cfgPath, FileAttributes.Hidden);
            }
            //// 读取数据库配置
            //_builder = new DbContextOptionsBuilder<DbContext>();
            //_builder.UseSqlite(connStr);
            //// 创建数据库
            //if (!egg.IO.CheckFileExists(dbPath))
            //{
            //    using (GitDbContext context = new GitDbContext(_builder.Options))
            //    {
            //        // 初始化创建数据库
            //        context.EnsureCreatedSqlite();
            //    }
            //}
            // 加载配置
            this.Setting = Setting.LoadFromFile(egg.IO.GetClosedPath(cfgPath) + "setting.json");
            //// 清理列表
            //this.listView1.Items.Clear();
            //foreach (var setting in gitSetting.Commands)
            //{
            //    ListViewItem item = new ListViewItem(setting.Name);
            //    item.SubItems.Add(setting.Folder);
            //    item.SubItems.Add(setting.ChildFolder);
            //    item.SubItems.Add(setting.Branch);
            //    item.SubItems.Add(setting.SourceBranch);
            //    item.ImageIndex = 0;
            //    this.listView1.Items.Add(item);
            //}
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                FileName = this.Setting.Tools.VSCode,
                Arguments = $"\"{this.WorkFolder}\"",
            };
            Process.Start(startInfo);
        }

        private void FrmParent_FormClosing(object sender, FormClosingEventArgs e)
        {
            SetStatus("正在退出程序 ...");
            _frmConsole.Dispose();
            foreach (Form childForm in MdiChildren)
            {
                SetStatus($"正在关闭窗口 '{childForm.Text}' ...");
                childForm.Close();
            }
            Application.Exit();
            //Environment.Exit(0);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show($"{egg.Assembly.Name} Version {egg.Assembly.Version}", egg.Assembly.Name);
        }
    }
}
